/**
	Copyright (c) 2009 ATTi 
	All rights reserved.
	Author: Michael Shu
	Date: 12/28/2009
*/

public with sharing class SelectCaseAttachmentController {
	private String currentCaseId;
	private Boolean isSelectAll;
	public String selectedIdString{get;set;}
	public Boolean isAttachmentEmpty{get;set;}
	public Boolean isAttachmentNotEmpty {get;set;}
	public List<selAttClass> lattachment{get; set;}
	
	public SelectCaseAttachmentController(){
		lattachment = new List<selAttClass>();
		this.currentCaseId = ApexPages.currentPage().getParameters().get('caseId');
		List<Attachment> lexistAtt = [Select a.Id, a.BodyLength, a.CreatedBy.Name, a.LastModifiedBy.Name, a.LastModifiedDate, a.Name 
		                              from Attachment a 
		                              where a.ParentId =: currentCaseId and a.IsDeleted =: false
		                              Order by a.Name,a.LastModifiedDate];
		if(!lexistAtt.isEmpty()){
			for(Attachment a : lexistAtt){
				selAttClass sAtt = new selAttClass();
				sAtt.att = a;
				sAtt.lastModDate = a.LastModifiedDate.format();
				lattachment.add(sAtt);
			}
		}
		this.isAttachmentEmpty = lattachment.isEmpty();
		this.isAttachmentNotEmpty = !lattachment.isEmpty();
		this.isSelectAll = false;
		this.selectedIdString = ''; 
	}
	
    public class selAttClass{
    	public Attachment att{get;set;}
    	public Boolean isSelected {get;set;}
    	public String lastModDate {get;set;}
    	
    	public selAttClass(){
    		isSelected = false;
    	}
    }	
    
    public void refreshSelectedIdString(){
    	selectedIdString = '';
		if(!lattachment.isEmpty()){
			for(selAttClass selAtt : lattachment){
				System.debug('Test1 selAtt.att.Name = ' + selAtt.att.Name + '; selAtt.isSelected = ' + selAtt.isSelected);
				if(selAtt.isSelected){
					String idTostring = selAtt.att.Id;
					selectedIdString += idTostring + ';';
				}
			}
			if(selectedIdString.contains(';')){
				selectedIdString = selectedIdString.substring(0, selectedIdString.lastIndexOf(';')); 
			}
		}
   }
    
    public PageReference selectAll(){
    	if(!isSelectAll){
    		for(selAttClass selAtt : lattachment){
    			selAtt.isSelected = true;
    		}
    		isSelectAll = true;
    	}else{
    		for(selAttClass selAtt : lattachment){
    			selAtt.isSelected = false;
    		}
    		isSelectAll = false;
    	}
    	refreshSelectedIdString();
    	return null;
    }
}